<template>
  <div class="ide-layout">
    <!-- 顶部工具栏 -->
    <div class="ide-toolbar">
      <div class="toolbar-left">
        <div class="project-info">
          <el-icon size="16" color="#409EFF"><Folder /></el-icon>
          <span class="project-name">{{ currentProject?.name || t('project.noProject') }}</span>
          <el-button text size="small" @click="closeProject" v-if="currentProject">
            <el-icon style="color: white;"><Close /></el-icon>
          </el-button>
        </div>
        
        <!-- 侧边栏切换按钮 -->
        <el-button 
          text 
          size="small" 
          @click="toggleSidebar"
          class="sidebar-toggle"
        >
          <el-icon><Menu /></el-icon>
        </el-button>
        <span v-if="currentFile" class="file-path breadcrumb">{{ currentFile.path }}</span>
      </div>
      
      <div class="toolbar-right">
        <el-tooltip :content="isRunning ? t('toolbar.stopAutomation') : t('toolbar.runAutomation')" placement="bottom">
          <el-button 
            :type="isRunning ? 'danger' : 'success'" 
            size="small" 
            @click="isRunning ? stopAutomation() : runAutomation()"
          >
            <span class="run-button">
              <i class="el-icon" v-if="!isRunning">
                <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1024 1024">
                  <path fill="currentColor" d="M384 192v640l384-320.064z"></path>
                </svg>
              </i>
              <i class="el-icon" v-else>
                <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1024 1024">
                  <path fill="currentColor" d="M256 192h512v640H256z"></path>
                </svg>
              </i>
              {{ isRunning ? t('common.stop') : t('common.run') }}
            </span>
          </el-button>
        </el-tooltip>
      </div>
      
    </div>

    <!-- 主内容区域 -->
    <div class="ide-content">
      <!-- 左侧文件树 -->
      <div class="file-explorer" :style="{ width: sidebarWidth + 'px' }" v-show="showSidebar">
        <div class="explorer-header">
          <h3>{{ t('project.projectFiles') }}</h3>
          <el-button text size="small" @click="refreshFiles">
            <el-icon><Refresh /></el-icon>
          </el-button>
        </div>
        
        <div class="file-tree" @contextmenu="handleFileTreeContextMenu">
          <el-tree
            :data="fileTreeData"
            :props="treeProps"
            node-key="path"
            :default-expanded-keys="expandedKeys"
            :expand-on-click-node="false"
            :highlight-current="true"
            @node-click="handleFileClick"
            class="file-tree-component"
          >
            <template #default="{ node, data }">
              <div class="tree-node" @contextmenu="(event) => handleNodeContextMenu(event, data)">
                <!-- 文件夹图标 -->
                <el-icon v-if="data.isDirectory">
                  <Folder v-if="!node.expanded" />
                  <FolderOpened v-else />
                </el-icon>
                <!-- 文件图标 -->
                <el-icon v-else-if="data.type === 'lua'">
                  <Document />
                </el-icon>
                <el-icon v-else-if="data.type === 'csv'">
                  <Document />
                </el-icon>
                <el-icon v-else-if="data.type === 'json'">
                  <Document />
                </el-icon>
                <el-icon v-else-if="data.type === 'javascript'">
                  <Document />
                </el-icon>
                <el-icon v-else-if="data.type === 'typescript'">
                  <Document />
                </el-icon>
                <el-icon v-else-if="data.type === 'vue'">
                  <Document />
                </el-icon>
                <el-icon v-else-if="data.type === 'css'">
                  <Document />
                </el-icon>
                <el-icon v-else-if="data.type === 'html'">
                  <Document />
                </el-icon>
                <el-icon v-else-if="data.type === 'text' || data.type === 'markdown'">
                  <Document />
                </el-icon>
                <el-icon v-else>
                  <Document />
                </el-icon>
                <span class="file-name">{{ data.name }}</span>
              </div>
            </template>
          </el-tree>
        </div>
      </div>

      <!-- 右键菜单 -->
      <teleport to="body">
      <div 
        v-show="contextMenuVisible" 
        class="context-menu"
        :style="{ left: contextMenuX + 'px', top: contextMenuY + 'px' }"
        @click.stop
      >
        <!-- 空白区域菜单 -->
        <template v-if="!contextTarget">
          <div class="context-menu-item" @click="createNewFile">
            <el-icon><DocumentAdd /></el-icon>
            <span>{{ $t('file.newFile') }}...</span>
          </div>
          <div class="context-menu-item" @click="createNewFolder">
            <el-icon><FolderAdd /></el-icon>
            <span>{{ $t('file.newFolder') }}...</span>
          </div>
          <div class="context-menu-separator"></div>
          <div class="context-menu-item" @click="addToWorkspace">
            <el-icon><Plus /></el-icon>
            <span>{{ $t('file.addToWorkspace') }}...</span>
          </div>
          <div class="context-menu-item" @click="openFolderSettings">
            <el-icon><Setting /></el-icon>
            <span>{{ $t('project.folderSettings') }}</span>
          </div>
          <div class="context-menu-item" @click="removeFromWorkspace">
            <el-icon><Delete /></el-icon>
            <span>{{ $t('file.removeFromWorkspace') }}</span>
          </div>
          <div class="context-menu-separator"></div>
          <div class="context-menu-item" @click="findInFolder">
            <el-icon><Search /></el-icon>
            <span>{{ $t('file.findInFolder') }}...</span>
            <span class="shortcut">Shift+Alt+F</span>
          </div>
          <div class="context-menu-item" @click="pasteFile">
            <el-icon><Document /></el-icon>
            <span>{{ $t('file.pasteFile') }}</span>
            <span class="shortcut">Ctrl+V</span>
          </div>
        </template>
        
        <!-- 文件节点菜单 -->
        <template v-if="contextTarget">
          <div class="context-menu-item" @click="openRename">
            <el-icon><Document /></el-icon>
            <span>{{ $t('file.renameFile') }}</span>
          </div>
          <div class="context-menu-item" @click="deleteTarget">
            <el-icon><Delete /></el-icon>
            <span>{{ $t('file.deleteFile') }}</span>
          </div>
        </template>
        
        <!-- 通用菜单项 -->
        <div class="context-menu-separator"></div>
        <div class="context-menu-item" @click="revealInExplorer">
          <el-icon><FolderOpened /></el-icon>
          <span>{{ $t('file.revealInExplorer') }}</span>
          <span class="shortcut">Shift+Alt+R</span>
        </div>
        <div class="context-menu-item" @click="copyPath">
          <el-icon><CopyDocument /></el-icon>
          <span>{{ $t('file.copyPath') }}</span>
          <span class="shortcut">Shift+Alt+C</span>
        </div>
        <div class="context-menu-item" @click="copyRelativePath">
          <el-icon><CopyDocument /></el-icon>
          <span>{{ $t('file.copyRelativePath') }}</span>
          <span class="shortcut">Ctrl+M Ctrl+Shift+C</span>
        </div>
      </div>

      <!-- 重命名输入框（浮层） -->
      <div 
        v-show="showRenameInput"
        class="new-file-popover"
        :style="{ left: renameX + 'px', top: renameY + 'px' }"
        @click.stop
      >
        <div class="new-file-inner">
          <el-icon class="nf-icon"><Document /></el-icon>
          <input
            ref="renameInputRef"
            v-model="renameName"
            class="new-file-input"
            type="text"
            spellcheck="false"
            :placeholder="$t('file.renameFile') + '...'"
            @keydown.enter.prevent="confirmRename"
            @keydown.esc.prevent="cancelRename"
          />
        </div>
      </div>
      
      <!-- 新建文件输入框（浮层） -->
      <div 
        v-show="showNewFileInput" 
        class="new-file-popover"
        :style="{ left: newFileX + 'px', top: newFileY + 'px' }"
        @click.stop
      >
        <div class="new-file-inner">
          <el-icon class="nf-icon"><Document /></el-icon>
          <input
            ref="newFileInputRef"
            v-model="newFileName"
            class="new-file-input"
            type="text"
            spellcheck="false"
            :placeholder="$t('file.newFile') + '...'"
            @keydown.enter.prevent="confirmCreateNewFile"
            @keydown.esc.prevent="cancelCreateNewFile"
          />
        </div>
      </div>
      </teleport>
      
      <!-- 拖拽条 -->
      <div 
        class="resize-handle" 
        v-show="showSidebar"
        @mousedown="startResize"
      ></div>

      <!-- 右侧编辑器区域 -->
      <div class="editor-area" v-if="!showSettings">
        <!-- 编辑器标签页 -->
        <div class="editor-tabs" v-if="openFiles.length > 0">
          <div
            v-for="file in openFiles"
            :key="file.path"
            class="tab-item"
            :class="{ active: currentFile?.path === file.path }"
            @click="switchFile(file)"
          >
            <el-icon>
              <Document />
            </el-icon>
            <span class="tab-name">{{ file.name }}</span>
            <span v-if="file.modified" class="modified-indicator" title="文件已修改"></span>
            <el-button
              text
              size="small"
              @click.stop="closeFile(file)"
              class="tab-close"
            >
              <el-icon><Close /></el-icon>
            </el-button>
          </div>
        </div>

        <!-- 代码编辑器 -->
        <div class="code-editor" v-if="currentFile">
          <div class="editor-header"></div>
          
          <div class="editor-content">
            <textarea
              ref="codeEditor"
              v-model="currentFileContent"
              class="code-textarea"
              :placeholder="getEditorPlaceholder()"
              @input="onContentChange"
              @keydown="onKeyDown"
            ></textarea>
          </div>
        </div>

        <!-- 空状态 -->
        <div v-else class="empty-editor">
          <el-empty :description="t('editor.selectFile')">
            <el-button type="primary" @click="createNewFile">
              <el-icon><DocumentAdd /></el-icon>
              {{ t('file.newFile') }}
            </el-button>
          </el-empty>
        </div>
      </div>
      
      <SettingsPanel v-if="showSettings" @close="showSettings = false" />
      
    </div>

    <!-- 底部状态栏 -->
    <StatusBar 
      :status="currentStatus"
      :status-text="statusText"
      :status-type="statusTypeComputed"
      :file-info="currentFile ? `${currentFile.name} | ${t('common.line')} ${currentLine} | ${t('common.column')} ${currentColumn}` : ''"
      :show-log="showLogPanel"
      @toggle-log="toggleLogPanel"
    />

    <!-- 日志面板 -->
    <LogPanel 
      v-show="showLogPanel" 
      :logs="logs" 
      :height="logPanelHeight"
      @clear="clearLogs"
      @resize="handleLogResize"
    />
    
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted, watch, nextTick, getCurrentInstance } from 'vue'
import { useGlobalSettingsStore } from '@/stores/globalSettings'
import { ElMessage } from 'element-plus'
import { showMessage, fileUtils } from '@/utils/common'
import { defineAsyncComponent } from 'vue'
import { useI18n } from 'vue-i18n'
import LogPanel from '@/components/LogPanel.vue'
const SettingsPanel = defineAsyncComponent(() => import('@/components/SettingsPanel.vue'))
const StatusBar = defineAsyncComponent(() => import('@/components/StatusBar.vue'))
// 使用全局常量
const SIMULATION_STATUS = getCurrentInstance()?.appContext.config.globalProperties.$SIMULATION_STATUS
const STATUS_TYPES = getCurrentInstance()?.appContext.config.globalProperties.$STATUS_TYPES
import projectService, { type ProjectInfo } from '@/services/projectService'


// 使用i18n
const { t } = useI18n()

// 使用全局router
const router = getCurrentInstance()?.appContext.config.globalProperties.$router

// 路由导航函数
const navigateTo = (path: string) => {
  if (router) {
    router.push(path)
  }
}

// 当前项目
const currentProject = ref<ProjectInfo | null>(null)

// 侧边栏状态
const showSidebar = ref(true)
const sidebarWidth = ref(300)
const isResizing = ref(false)

// 右键菜单状态
const contextMenuVisible = ref(false)
const contextMenuX = ref(0)
const contextMenuY = ref(0)

// 节点右键目标（文件/文件夹）
const contextTarget = ref<any | null>(null)

// 新建文件浮层状态
const showNewFileInput = ref(false)
const newFileName = ref('')
const newFileX = ref(0)
const newFileY = ref(0)
const newFileInputRef = ref<HTMLInputElement>()

// 文件树数据
const fileTreeData = ref<any[]>([])
const treeProps = {
  children: 'children',
  label: 'name'
}

// 打开项目时默认展开项目根目录
const expandedKeys = ref<string[]>([])

// 打开的文件
const openFiles = ref<any[]>([])
const currentFile = ref<any>(null)
const currentFileContent = ref('')

// 撤销历史记录
const undoHistory = ref<string[]>([])
const undoIndex = ref(-1)

// 编辑器状态
const currentLine = ref(1)
const currentColumn = ref(1)
const isLoadingFile = ref(false) // 防止文件加载时触发内容变化事件
const codeEditor = ref<HTMLTextAreaElement>()

// 状态栏状态
const currentStatus = ref(SIMULATION_STATUS.WAITING)
const statusText = ref(t('status.ready'))

// 运行状态
const isRunning = ref(false)

// 日志面板
const showLogPanel = ref(false)
const logPanelHeight = ref(500) // 默认高度500px

// 本地日志管理
interface LogItem {
  timestamp: Date
  level: 'info' | 'warn' | 'error' | 'success'
  message: string
}

const logs = ref<LogItem[]>([])
let logPollingInterval: number | null = null

// 添加日志
const addLog = (level: 'info' | 'warn' | 'error' | 'success', message: string) => {
  logs.value.push({
    timestamp: new Date(),
    level,
    message
  })
  
  // 限制日志数量，避免内存泄漏
  if (logs.value.length > 1000) {
    logs.value = logs.value.slice(-500)
  }
}

// 清空日志
const clearLogs = () => {
  logs.value = []
}

// 格式化运行时间
const formatRuntime = (seconds: number): string => {
  if (seconds < 60) {
    return `${seconds.toFixed(1)}${t('common.seconds')}`
  } else if (seconds < 3600) {
    const minutes = Math.floor(seconds / 60)
    const remainingSeconds = Math.floor(seconds % 60)
    return `${minutes}${t('common.minutes')}${remainingSeconds}${t('common.seconds')}`
  } else {
    const hours = Math.floor(seconds / 3600)
    const minutes = Math.floor((seconds % 3600) / 60)
    const remainingSeconds = Math.floor(seconds % 60)
    return `${hours}${t('common.hours')}${minutes}${t('common.minutes')}${remainingSeconds}${t('common.seconds')}`
  }
}

// 获取Python后端日志
const fetchPythonLogs = async () => {
  try {
    if ((window as any).electronAPI && (window as any).electronAPI.getSimionLogs) {
      const result = await (window as any).electronAPI.getSimionLogs()
      if (result.success && result.logs && result.logs.length > 0) {
        result.logs.forEach((log: any) => {
          // 过滤掉HTTP请求日志
          if (log.message && (
            log.message.includes('127.0.0.1') && 
            log.message.includes('GET /logs HTTP/1.1') ||
            log.message.includes('GET /status HTTP/1.1') ||
            log.message.includes('POST /run HTTP/1.1') ||
            log.message.includes('POST /stop HTTP/1.1') ||
            log.message.includes('HTTP/1.1" 200')
          )) {
            return // 跳过HTTP请求日志
          }
          
          // 转换Python日志级别到前端日志级别
          let level: 'info' | 'warn' | 'error' | 'success' = 'info'
          if (log.level === 'ERROR' || log.level === 'CRITICAL') {
            level = 'error'
          } else if (log.level === 'WARNING') {
            level = 'warn'
          } else if (log.level === 'INFO') {
          // 检查是否包含成功信息
          if (log.message && log.message.includes('自动化运行结果') && log.message.includes("'success': True")) {
            level = 'success'
            // 提取运行时间信息并格式化显示
            const runtimeMatch = log.message.match(/运行时间: (\d+\.?\d*)秒/)
            if (runtimeMatch) {
              const runtime = parseFloat(runtimeMatch[1])
              const formattedTime = formatRuntime(runtime)
              log.message = log.message.replace(/运行时间: \d+\.?\d*秒/, `运行时间: ${formattedTime}`)
            }
          } else {
            level = 'info'
          }
          }
          
          addLog(level, log.message)
          
          // 检查是否有任务完成的信息
          if (log.message && log.message.includes('自动化运行结果')) {
            // 延迟处理任务完成，确保所有日志都被获取
            setTimeout(async () => {
              try {
                // 再次获取日志以确保不遗漏任何信息
                await fetchPythonLogs()
                
                // 等待一下再停止轮询
                setTimeout(() => {
                  stopLogPolling()
                  currentStatus.value = SIMULATION_STATUS.COMPLETED
                  statusText.value = t('status.completed')
                  isRunning.value = false
                  addLog('info', t('messages.taskCompleted'))
                  addLog('info', t('messages.serverKeptRunning'))
                }, 2000) // 延迟2秒再停止轮询
              } catch (error) {
                console.error('获取最终日志失败:', error)
                // 即使出错也要停止轮询
                stopLogPolling()
                currentStatus.value = SIMULATION_STATUS.COMPLETED
                statusText.value = t('status.completed')
                isRunning.value = false
              }
            }, 1000) // 延迟1秒再处理
            return
          }
          
          // 检查是否有错误详情
          if (log.message && log.message.includes('错误详情')) {
            addLog('error', t('messages.taskExecutionError'))
          }
        })
      }
    }
  } catch (error) {
    console.error('获取Python日志失败:', error)
  }
}

// 开始轮询Python日志
const startLogPolling = () => {
  if (logPollingInterval) {
    clearInterval(logPollingInterval)
  }
  logPollingInterval = setInterval(fetchPythonLogs, 2000) // 每2秒获取一次
}

// 停止轮询Python日志
const stopLogPolling = () => {
  if (logPollingInterval) {
    clearInterval(logPollingInterval)
    logPollingInterval = null
  }
}

// 检查任务状态
const checkTaskStatus = async () => {
  try {
    if ((window as any).electronAPI && (window as any).electronAPI.getSimionStatus) {
      const status = await (window as any).electronAPI.getSimionStatus()
      
      // 检查服务器是否已关闭
      if (status && status.message && status.message.includes('Python服务器已关闭')) {
        stopLogPolling()
        currentStatus.value = SIMULATION_STATUS.COMPLETED
        statusText.value = '完成'
        isRunning.value = false
        addLog('info', 'Python服务器已关闭，任务完成')
        return
      }
      
      // 只有在明确检测到任务完成时才停止
      if (status && status.is_running === false && status.success_count !== undefined && status.failed_count !== undefined) {
        const total = status.success_count + status.failed_count
        if (total > 0 && status.success_count + status.failed_count === status.total_count) {
          // 所有任务已完成
          stopLogPolling()
          currentStatus.value = SIMULATION_STATUS.COMPLETED
          statusText.value = '完成'
          isRunning.value = false
          addLog('info', `任务已完成 - 成功: ${status.success_count}, 失败: ${status.failed_count}`)
          addLog('info', 'Python服务器保持运行状态')
          return
        }
      }
      
      // 任务仍在运行，继续检查（减少检查频率）
      setTimeout(checkTaskStatus, 30000) // 30秒后再次检查
    }
  } catch (error) {
    console.error('检查任务状态失败:', error)
    // 出错时不要立即停止，而是继续检查
    addLog('warn', '状态检查出错，继续监控任务')
    setTimeout(checkTaskStatus, 10000) // 10秒后再次检查
  }
}

// 计算属性
const statusTypeComputed = computed(() => {
  return STATUS_TYPES[currentStatus.value] || 'info'
})

// 获取编辑器占位符
const getEditorPlaceholder = () => {
  if (!currentFile.value) return '请选择一个文件进行编辑'
  
  const ext = currentFile.value.name.split('.').pop()?.toLowerCase()
  switch (ext) {
    case 'lua':
      return '-- 在这里编写 Lua 代码\n-- 支持 adjustable 参数配置\n\nadjustable _rfvolt = 5000\nadjustable _rfvolt2 = 2000\nadjustable _frequency = 1200000'
    case 'txt':
    case 'md':
      return '# 在这里编写文本内容'
    default:
      return '在这里编辑文件内容'
  }
}

// 加载项目文件
const loadProjectFiles = async () => {
  if (!currentProject.value) return
  
  try {
    // 从真实文件系统获取文件列表
    if ((window as any).electronAPI) {
      const result = await (window as any).electronAPI.listFiles(currentProject.value.path)
      if (result.success) {
        fileTreeData.value = buildFileTree(result.files, currentProject.value.path, currentProject.value.name)
        expandedKeys.value = [currentProject.value.path]
        
        // 检测IOB和Lua文件
        await detectAndSetProjectFiles()
      } else {
        throw new Error(result.error || '获取文件列表失败')
      }
    } else {
      // 回退到空数据
      fileTreeData.value = []
      expandedKeys.value = []
    }
  } catch (error) {
    console.error('加载项目文件失败:', error)
    ElMessage.error(t('messages.loadProjectFilesFailed'))
  }
}

// 检测并设置项目文件
const detectAndSetProjectFiles = async () => {
  if (!currentProject.value) return
  
  try {
    const globalSettings = useGlobalSettingsStore()
    
    // 设置项目路径
    if (globalSettings.setProjectPath) {
      globalSettings.setProjectPath(currentProject.value.path)
    }
    
    // 检测IOB和Lua文件
    const result = await globalSettings.detectProjectFiles(currentProject.value.path)
    
    if (result.success) {
      if (result.matchedPairs.length > 0) {
        // 使用第一个匹配的文件对
        const firstPair = result.matchedPairs[0]
        if (firstPair) {
          globalSettings.setFilePaths(firstPair.iob, firstPair.lua)
          // 如果有多个匹配对，显示信息
          if (result.matchedPairs.length > 1) {
            addLog('info', `共找到 ${result.matchedPairs.length} 个匹配的文件对，使用第一个`)
          }
        }
      } else {
        // 没有匹配的文件对
        if (result.iobFiles.length > 0 && result.luaFiles.length > 0) {
          addLog('warn', '找到IOB和Lua文件，但没有匹配的文件对')
        } else if (result.iobFiles.length > 0) {
          addLog('warn', `只找到IOB文件: ${result.iobFiles.join(', ')}`)
        } else if (result.luaFiles.length > 0) {
          addLog('warn', `只找到Lua文件: ${result.luaFiles.join(', ')}`)
        } else {
          addLog('warn', '项目目录中未找到IOB或Lua文件')
        }
      }
    } else {
      addLog('error', `检测项目文件失败: ${result.error}`)
    }
  } catch (error) {
    console.error('检测项目文件失败:', error)
    addLog('error', `检测项目文件失败: ${error}`)
  }
}

// 构建文件树结构
const buildFileTree = (files: any[], rootPath: string, rootName: string) => {
  const tree: any = {
    name: rootName,
    path: rootPath,
    type: 'folder',
    children: [],
    isDirectory: true
  }
  
  // 按路径分组文件
  const pathMap = new Map<string, any[]>()
  
  files.forEach(file => {
    const relativePath = file.path.replace(rootPath, '').replace(/^[\/\\]/, '')
    const pathParts = relativePath.split(/[\/\\]/)
    
    if (pathParts.length === 1) {
      // 根目录文件
      if (!pathMap.has('')) {
        pathMap.set('', [])
      }
      pathMap.get('')!.push(file)
    } else {
      // 子目录文件
      const dirPath = pathParts[0]
      if (!pathMap.has(dirPath)) {
        pathMap.set(dirPath, [])
      }
      pathMap.get(dirPath)!.push(file)
    }
  })
  
  // 构建目录结构
  pathMap.forEach((dirFiles, dirPath) => {
    if (dirPath === '') {
      // 根目录文件
      dirFiles.forEach(file => {
        tree.children.push({
          name: file.name,
          path: file.path,
          type: file.isDirectory ? 'folder' : getFileType(file.name),
          isDirectory: file.isDirectory,
          children: file.isDirectory ? [] : undefined
        })
      })
    } else {
      // 子目录
      const dirNode = {
        name: dirPath,
        path: `${rootPath}/${dirPath}`,
        type: 'folder',
        isDirectory: true,
        children: dirFiles.map(file => ({
          name: file.name,
          path: file.path,
          type: file.isDirectory ? 'folder' : getFileType(file.name),
          isDirectory: file.isDirectory,
          children: file.isDirectory ? [] : undefined
        }))
      }
      tree.children.push(dirNode)
    }
  })
  
  return [tree]
}

// 根据文件扩展名确定文件类型
const getFileType = (fileName: string): string => {
  const ext = fileName.split('.').pop()?.toLowerCase()
  switch (ext) {
    case 'lua':
      return 'lua'
    case 'txt':
      return 'text'
    case 'md':
      return 'markdown'
    case 'csv':
      return 'csv'
    case 'json':
      return 'json'
    case 'js':
      return 'javascript'
    case 'ts':
      return 'typescript'
    case 'vue':
      return 'vue'
    case 'css':
      return 'css'
    case 'html':
      return 'html'
    default:
      return 'other'
  }
}

// 处理文件点击
const handleFileClick = async (data: any) => {
  if (data.isDirectory) {
    // 如果是文件夹，展开/折叠
    await toggleFolder(data)
    return
  }
  
  // 检查文件是否已经打开
  const existingFile = openFiles.value.find(f => f.path === data.path)
  if (existingFile) {
    isLoadingFile.value = true // 设置加载标志
    
    currentFile.value = existingFile
    currentFileContent.value = existingFile.content
    
    // 使用nextTick确保在DOM更新后清除加载标志
    nextTick(() => {
      isLoadingFile.value = false
    })
    return
  }
  
  // 打开新文件
  try {
    isLoadingFile.value = true // 设置加载标志
    
    const fileContent = await loadFileContent(data.path)
    const newFile = {
      ...data,
      content: fileContent,
      modified: false
    }
    
    openFiles.value.push(newFile)
    currentFile.value = newFile
    currentFileContent.value = fileContent
    
    // 初始化撤销历史
    resetUndoHistory()
    
    addLog('info' as const, `已打开文件: ${data.name}`)
  } catch (error) {
    ElMessage.error(`${t('messages.openFileFailed')}: ${data.name}`)
  } finally {
    // 使用nextTick确保在DOM更新后清除加载标志
    nextTick(() => {
      isLoadingFile.value = false
    })
  }
}

// 切换文件夹展开/折叠状态
const toggleFolder = async (folderData: any) => {
  try {
    // 如果文件夹还没有加载内容，先加载
    if (!folderData.children || folderData.children.length === 0) {
      await loadFolderContent(folderData)
    }
    
    // 切换展开状态
    const node = findTreeNodeByPath(folderData.path)
    if (node) {
      // 这里可以添加展开/折叠的视觉反馈
      console.log(`切换文件夹: ${folderData.name}`)
    }
  } catch (error) {
    console.error('切换文件夹失败:', error)
    ElMessage.error(`${t('messages.cannotAccessFolder')}: ${folderData.name}`)
  }
}

// 加载文件夹内容
const loadFolderContent = async (folderData: any) => {
  try {
    if ((window as any).electronAPI) {
      const result = await (window as any).electronAPI.listFiles(folderData.path)
      if (result.success) {
        // 构建子节点
        const children = result.files.map((file: any) => ({
          name: file.name,
          path: file.path,
          type: file.isDirectory ? 'folder' : getFileType(file.name),
          isDirectory: file.isDirectory,
          children: file.isDirectory ? [] : undefined
        }))
        
        // 更新文件夹的children
        folderData.children = children
        
        addLog('info', `已加载文件夹内容: ${folderData.name} (${children.length} 项)`)
      } else {
        throw new Error(result.error || '获取文件夹内容失败')
      }
    }
  } catch (error) {
    console.error('加载文件夹内容失败:', error)
    ElMessage.error(`${t('messages.loadFolderContentFailed')}: ${folderData.name}`)
  }
}

// 根据路径查找树节点
const findTreeNodeByPath = (path: string): any => {
  const searchInTree = (nodes: any[]): any => {
    for (const node of nodes) {
      if (node.path === path) {
        return node
      }
      if (node.children) {
        const found = searchInTree(node.children)
        if (found) return found
      }
    }
    return null
  }
  
  return searchInTree(fileTreeData.value)
}

// 加载文件内容
const loadFileContent = async (filePath: string): Promise<string> => {
  try {
    if ((window as any).electronAPI) {
      const result = await (window as any).electronAPI.readFile(filePath)
      if (result.success) {
        return result.content
      } else {
        throw new Error(result.error || '读取文件失败')
      }
    } else {
      // 返回空内容
      return ''
    }
  } catch (error) {
    throw new Error(`读取文件失败: ${error}`)
  }
}

// 切换文件
const switchFile = (file: any) => {
  isLoadingFile.value = true // 设置加载标志
  
  currentFile.value = file
  currentFileContent.value = file?.content || ''
  
  // 重置撤销历史
  resetUndoHistory()
  
  // 使用nextTick确保在DOM更新后清除加载标志
  nextTick(() => {
    isLoadingFile.value = false
  })
}

// 关闭文件
const closeFile = (file: any) => {
  const index = openFiles.value.findIndex(f => f.path === file.path)
  if (index > -1) {
    openFiles.value.splice(index, 1)
    
    if (currentFile.value?.path === file.path) {
      if (openFiles.value.length > 0) {
        currentFile.value = openFiles.value[0]
        currentFileContent.value = currentFile.value?.content || ''
      } else {
        currentFile.value = null
        currentFileContent.value = ''
      }
    }
  }
}

// 保存文件
const saveFile = async () => {
  if (!currentFile.value) {
    ElMessage.warning(t('messages.noFileToSave'))
    return
  }
  
  try {
    if ((window as any).electronAPI) {
      await (window as any).electronAPI.writeFile(
        currentFile.value.path,
        currentFileContent.value
      )
      currentFile.value.content = currentFileContent.value
      currentFile.value.modified = false
      
      ElMessage.success({
        message: t('messages.fileSaved'),
        duration: 2000
      })
    } else {
      ElMessage.error(t('messages.saveFileFailed'))
    }
  } catch (error) {
    console.error('保存文件失败:', error)
    ElMessage.error(`${t('messages.saveFileFailed')}: ${(error as Error).message}`)
  }
}

// 内容变化处理
const onContentChange = () => {
  // 如果正在加载文件，不触发修改标记
  if (isLoadingFile.value) {
    return
  }
  
  if (currentFile.value) {
    currentFile.value.modified = true
    updateCursorPosition()
    
    // 添加到撤销历史
    addToUndoHistory(currentFileContent.value)
  }
}

// 添加到撤销历史
const addToUndoHistory = (content: string) => {
  // 如果当前内容与历史记录中的最新内容相同，则不添加
  if (undoHistory.value.length > 0 && undoHistory.value[undoIndex.value] === content) {
    return
  }
  
  // 移除当前位置之后的所有历史记录
  undoHistory.value = undoHistory.value.slice(0, undoIndex.value + 1)
  
  // 添加新内容
  undoHistory.value.push(content)
  undoIndex.value = undoHistory.value.length - 1
  
  // 限制历史记录数量（最多50个）
  if (undoHistory.value.length > 50) {
    undoHistory.value.shift()
    undoIndex.value--
  }
}

// 撤销编辑
const undoEdit = () => {
  if (undoIndex.value > 0) {
    undoIndex.value--
    const previousContent = undoHistory.value[undoIndex.value]
    currentFileContent.value = previousContent || ''
    
    if (currentFile.value) {
      currentFile.value.content = previousContent || ''
      currentFile.value.modified = true
    }
    
    ElMessage.success({
      message: t('messages.undoSuccess'),
      duration: 2000
    })
  } else {
    ElMessage.warning(t('messages.nothingToUndo'))
  }
}

// 重置撤销历史
const resetUndoHistory = () => {
  undoHistory.value = []
  undoIndex.value = -1
  
  // 如果当前有文件，添加初始内容到历史记录
  if (currentFile.value && currentFileContent.value) {
    // 直接添加到历史记录，不触发修改状态
    undoHistory.value.push(currentFileContent.value)
    undoIndex.value = 0
  }
}

// 更新光标位置
const updateCursorPosition = () => {
  if (!codeEditor.value) return
  
  const textarea = codeEditor.value
  const text = textarea.value
  const cursorPos = textarea.selectionStart
  
  const lines = text.substring(0, cursorPos).split('\n')
  currentLine.value = lines.length
  currentColumn.value = (lines[lines.length - 1]?.length || 0) + 1
}

// 键盘事件处理
const onKeyDown = (event: KeyboardEvent) => {
  // Ctrl+S 保存
  if (event.ctrlKey && event.key === 's') {
    event.preventDefault()
    saveFile()
  }
  
  // 移除格式化快捷键
  
  // Ctrl+B 切换侧边栏
  if (event.ctrlKey && event.key === 'b') {
    event.preventDefault()
    toggleSidebar()
  }
}

// 刷新文件
const refreshFiles = () => {
  loadProjectFiles()
  ElMessage.success({
    message: t('messages.filesRefreshed'),
    duration: 3000
  })
}

// 关闭项目
const closeProject = () => {
  projectService.closeCurrentProject()
  currentProject.value = null
  openFiles.value = []
  currentFile.value = null
  currentFileContent.value = ''
  fileTreeData.value = []
  ElMessage.success({
    message: t('messages.projectClosed'),
    duration: 3000
  })
  navigateTo('/welcome')
}

// 切换侧边栏显示/隐藏
const toggleSidebar = () => {
  showSidebar.value = !showSidebar.value
}

// 开始调节宽度
const startResize = (e: MouseEvent) => {
  isResizing.value = true
  document.addEventListener('mousemove', handleResize)
  document.addEventListener('mouseup', stopResize)
  e.preventDefault()
}

// 处理宽度调节
const handleResize = (e: MouseEvent) => {
  if (!isResizing.value) return
  
  const newWidth = e.clientX
  if (newWidth >= 100 && newWidth <= 600) {
    sidebarWidth.value = newWidth
  }
}

// 停止调节宽度
const stopResize = () => {
  isResizing.value = false
  document.removeEventListener('mousemove', handleResize)
  document.removeEventListener('mouseup', stopResize)
}

// 切换日志面板
const toggleLogPanel = () => {
  showLogPanel.value = !showLogPanel.value
}

// 处理日志面板高度调整
const handleLogResize = (newHeight: number) => {
  logPanelHeight.value = newHeight
}



// 监听文件内容变化
watch(currentFileContent, () => {
  if (currentFile.value && !isLoadingFile.value) {
    currentFile.value.content = currentFileContent.value
    currentFile.value.modified = true
  } else if (currentFile.value && isLoadingFile.value) {
    // 如果正在加载文件，只更新内容，不标记为已修改
    currentFile.value.content = currentFileContent.value
  }
})

// 处理文件树右键菜单

// 处理文件树空白区域右键菜单
const handleFileTreeContextMenu = (event: MouseEvent) => {
  // 仅在点击文件树空白区域时弹出（节点上有 .tree-node）
  const target = event.target as HTMLElement
  const nodeEl = target.closest('.tree-node') as HTMLElement | null
  if (nodeEl) {
    // 如果点击的是节点，不处理（由 handleNodeContextMenu 处理）
    return
  }
  
  // 空白处：清理目标，显示空白菜单
  contextTarget.value = null
  showContextMenu(event)
}

// 处理文件节点右键菜单
const handleNodeContextMenu = (event: MouseEvent, data: any) => {
  event.preventDefault()
  contextTarget.value = data
  showContextMenu(event)
}

// 显示右键菜单的通用方法
const showContextMenu = (event: MouseEvent) => {
  // 定位到鼠标位置，并限制在视口内
  const margin = 8
  const menuWidth = 260
  const menuHeight = 280
  const vw = window.innerWidth
  const vh = window.innerHeight
  let x = event.clientX
  let y = event.clientY
  if (x + menuWidth + margin > vw) x = vw - menuWidth - margin
  if (y + menuHeight + margin > vh) y = vh - menuHeight - margin
  contextMenuX.value = Math.max(margin, x)
  contextMenuY.value = Math.max(margin, y)

  nextTick(() => {
    contextMenuVisible.value = true
  })
}

const findNodeByPath = (nodes: any[], pathKey: string): any | null => {
  for (const n of nodes) {
    if (n.path === pathKey) return n
    if (n.children) {
      const sub = findNodeByPath(n.children, pathKey)
      if (sub) return sub
    }
  }
  return null
}

// 隐藏右键菜单
const hideContextMenu = () => {
  contextMenuVisible.value = false
}

// 新建文件
const createNewFile = () => {
  // 在右键菜单附近显示输入框
  hideContextMenu()
  newFileName.value = ''
  newFileX.value = contextMenuX.value + 8
  newFileY.value = contextMenuY.value + 8
  showNewFileInput.value = true
  nextTick(() => newFileInputRef.value?.focus())
}

const cancelCreateNewFile = () => {
  showNewFileInput.value = false
}

const confirmCreateNewFile = async () => {
  const name = newFileName.value.trim()
  if (!name) {
    showNewFileInput.value = false
    return
  }
  if (!currentProject.value) return
  try {
    const fullPath = `${currentProject.value.path}/${name}`
    if ((window as any).electronAPI) {
      // 若已存在则提示
      const exists = await (window as any).electronAPI.fileExists(fullPath)
      if (exists?.exists) {
        ElMessage.warning(t('messages.fileExists'))
        return
      }
      const writeRes = await (window as any).electronAPI.writeFile(fullPath, '')
      if (!writeRes?.success) throw new Error(writeRes?.error || '创建失败')
    }
    // 刷新树并打开文件
    await loadProjectFiles()
    const newNode = { name, path: fullPath, type: getFileType(name), content: '' }
    openFiles.value.unshift(newNode)
    currentFile.value = newNode
    currentFileContent.value = ''
    ElMessage.success({
      message: t('messages.fileCreated'),
      duration: 3000
    })
  } catch (e) {
    ElMessage.error(`${t('messages.createFileFailed')}: ${(e as Error).message}`)
  } finally {
    showNewFileInput.value = false
  }
}

// 新建文件夹
const createNewFolder = () => {
  hideContextMenu()
  ElMessage.info(t('messages.newFolderFeature'))
}

// 在文件资源管理器中显示
const revealInExplorer = () => {
  hideContextMenu()
  const targetPath = contextTarget.value?.path || currentProject.value?.path
  if (!targetPath) return
  if ((window as any).electronAPI) {
    ;(window as any).electronAPI.revealInExplorer(targetPath)
  }
}

// 在集成终端中打开（已移除）

// 添加到工作区
const addToWorkspace = () => {
  hideContextMenu()
  ElMessage.info(t('messages.addToWorkspaceFeature'))
}

// 打开文件夹设置
const openFolderSettings = () => {
  hideContextMenu()
  ElMessage.info(t('messages.openFolderSettingsFeature'))
}

// 从工作区删除
const removeFromWorkspace = () => {
  hideContextMenu()
  ElMessage.info(t('messages.removeFromWorkspaceFeature'))
}

// 在文件夹中查找
const findInFolder = () => {
  hideContextMenu()
  ElMessage.info(t('messages.findInFolderFeature'))
}

// 粘贴文件
const pasteFile = () => {
  hideContextMenu()
  ElMessage.info(t('messages.pasteFileFeature'))
}

// 复制路径
const copyPath = async () => {
  hideContextMenu()
  const targetPath = contextTarget.value?.path || currentProject.value?.path
  if (targetPath) {
    const success = await fileUtils.copyToClipboard(targetPath)
    if (success) {
      showMessage.success('路径已复制到剪贴板')
    } else {
      showMessage.error('复制失败')
    }
  }
}

// 复制相对路径
const copyRelativePath = async () => {
  hideContextMenu()
  if (currentProject.value) {
    const targetPath = contextTarget.value?.path || currentProject.value.path
    const relativePath = targetPath.replace(currentProject.value.path, '').replace(/^\\|\//, '') || '.'
    const success = await fileUtils.copyToClipboard(relativePath)
    if (success) {
      showMessage.success('相对路径已复制到剪贴板')
    } else {
      showMessage.error('复制失败')
    }
  }
}

const deleteTarget = async () => {
  hideContextMenu()
  if (!contextTarget.value) return
  const ok = confirm(`${t('common.confirm')}${t('file.deleteFile')}: ${contextTarget.value.name} ?`)
  if (!ok) return
  if ((window as any).electronAPI) {
    const res = await (window as any).electronAPI.deleteFile(contextTarget.value.path)
    if (!res?.success) {
      ElMessage.error(res?.error || t('messages.deleteFileFailed'))
      return
    }
  }
  await loadProjectFiles()
  if (currentFile.value?.path === contextTarget.value.path) {
    currentFile.value = null
    currentFileContent.value = ''
  }
  ElMessage.success({
    message: t('messages.fileDeleted'),
    duration: 3000
  })
}

// 重命名：以输入浮层方式
const showRenameInput = ref(false)
const renameX = ref(0)
const renameY = ref(0)
const renameName = ref('')
const renameInputRef = ref<HTMLInputElement>()

const openRename = () => {
  hideContextMenu()
  if (!contextTarget.value) return
  renameName.value = contextTarget.value.name
  renameX.value = contextMenuX.value + 8
  renameY.value = contextMenuY.value + 8
  showRenameInput.value = true
  nextTick(() => renameInputRef.value?.focus())
}

const confirmRename = async () => {
  if (!contextTarget.value || !currentProject.value) return
  const newName = renameName.value.trim()
  if (!newName) { showRenameInput.value = false; return }
  const oldPath = contextTarget.value.path
  const sep = oldPath.includes('\\') ? '\\' : '/'
  const baseDir = oldPath.substring(0, oldPath.lastIndexOf(sep))
  const newPath = `${baseDir}${sep}${newName}`
  if ((window as any).electronAPI) {
    const res = await (window as any).electronAPI.renameFile(oldPath, newPath)
    if (!res?.success) {
      ElMessage.error(res?.error || t('messages.renameFileFailed'))
      return
    }
  }
  await loadProjectFiles()
  if (currentFile.value?.path === oldPath) {
    currentFile.value.path = newPath
    currentFile.value.name = newName
  }
  showRenameInput.value = false
  ElMessage.success({
    message: t('messages.fileRenamed'),
    duration: 3000
  })
}

const cancelRename = () => {
  showRenameInput.value = false
}

// 运行SIMION自动化
const runAutomation = async () => {
  // 如果已经在运行，先停止当前任务
  if (isRunning.value) {
    addLog('warn', t('messages.taskRunning'))
    await stopAutomation()
    // 等待一下确保停止完成
    await new Promise(resolve => setTimeout(resolve, 1000))
  }
  
  // 清空之前的日志
  clearLogs()
  
  // 获取全局设置
  const globalSettings = useGlobalSettingsStore()
  
  // 首先检查Python服务器状态
  try {
    if ((window as any).electronAPI && (window as any).electronAPI.checkPythonServerStatus) {
      const serverStatus = await (window as any).electronAPI.checkPythonServerStatus()
      if (!serverStatus.success || !serverStatus.running) {
        ElMessage.error(`${t('messages.serverNotRunning')}: ${serverStatus.error || t('common.error')}`)
        addLog('error', `${t('messages.checkServerStatusFailed')}: ${serverStatus.error}`)
        
        // 尝试重启Python服务器
        ElMessage.info(t('messages.restartingPythonServer'))
        const restartResult = await (window as any).electronAPI.restartPythonServer()
        if (restartResult.success) {
          addLog('info', 'Python服务器重启中，请稍后重试')
          ElMessage.info(t('messages.serverRestarting'))
        } else {
          addLog('error', `重启Python服务器失败: ${restartResult.error}`)
          ElMessage.error(`${t('messages.serverRestartFailed')}: ${restartResult.error}`)
        }
        return
      } else {
        addLog('info', 'Python服务器状态正常')
      }
    }
  } catch (error) {
    console.error('检查Python服务器状态失败:', error)
    addLog('error', `检查Python服务器状态失败: ${error}`)
    ElMessage.error(t('messages.cannotCheckServerStatus'))
    return
  }
  
  // 验证SIMION路径
  if (!globalSettings.simionPath || globalSettings.simionPath.trim() === '') {
    ElMessage.error(t('messages.setSimionPath'))
    return
  }
  
  // 获取当前扫描参数
  const scanParams = globalSettings.getCurrentScanParams()
  
  // 验证扫描参数
  if (!scanParams.start || scanParams.start.trim() === '') {
    ElMessage.error(t('messages.setStartValue'))
    return
  }
  
  if (!scanParams.stop || scanParams.stop.trim() === '') {
    ElMessage.error(t('messages.setStopValue'))
    return
  }
  
  // 验证数值有效性
  const start = parseFloat(scanParams.start)
  const stop = parseFloat(scanParams.stop)
  const step = parseFloat(scanParams.step)
  
  if (isNaN(start) || isNaN(stop)) {
    ElMessage.error(t('messages.invalidNumbers'))
    return
  }
  
  // 如果开始值和停止值相同，步长可以为空
  if (start === stop) {
    if (scanParams.step && scanParams.step.trim() !== '') {
      if (isNaN(step) || step <= 0) {
        ElMessage.error(t('messages.stepMustBePositive'))
        return
      }
    }
    // 开始值和停止值相同时，直接使用单个值
  } else {
    // 开始值和停止值不同时，必须设置步长
    if (!scanParams.step || scanParams.step.trim() === '') {
      ElMessage.error(t('messages.stepRequired'))
      return
    }
    
    if (isNaN(step) || step <= 0) {
      ElMessage.error(t('messages.stepMustBePositive'))
      return
    }
    
    if (start >= stop) {
      ElMessage.error(t('messages.startLessThanStop'))
      return
    }
  }
  
  // 生成频率列表
  const frequencyList = []
  if (start === stop) {
    // 开始值和停止值相同，只添加一个值
    frequencyList.push(start)
  } else {
    // 开始值和停止值不同，按步长生成列表
    for (let freq = start; freq <= stop; freq += step) {
      frequencyList.push(freq)
    }
  }
  
  // 验证文件路径
  if (!globalSettings.iobPath || !globalSettings.luaPath) {
    ElMessage.error(t('messages.noMatchedFiles'))
    addLog('error', '未找到匹配的IOB和Lua文件')
    return
  }
  
  // 获取CPU核心数
  const cpuCores = navigator.hardwareConcurrency || 4 // 默认4核，如果无法获取
  
  // 构建配置对象
  const config = {
    simion_path: globalSettings.simionPath,
    iob_path: globalSettings.iobPath,
    lua_path: globalSettings.luaPath,
    csv_save_path: globalSettings.projectPath + '/output', // 输出目录
    frequency_list: frequencyList,
    thread_count: cpuCores,
    language: globalSettings.language // 语言参数
  }
  
  try {
    // 确保状态完全重置
    currentStatus.value = SIMULATION_STATUS.WAITING
    statusText.value = '准备就绪'
    isRunning.value = false
    
    // 停止任何现有的轮询
    stopLogPolling()
    
    // 自动弹出日志面板
    showLogPanel.value = true
    
    // 输出调试信息
    addLog('info', '=== SIMION自动化调试信息 ===')
    addLog('info', `SIMION路径: ${globalSettings.simionPath}`)
    addLog('info', `IOB路径: ${globalSettings.iobPath}`)
    addLog('info', `Lua路径: ${globalSettings.luaPath}`)
    addLog('info', `项目路径: ${globalSettings.projectPath}`)
    const outputPath = `${globalSettings.projectPath}/output`.replace(/\\/g, '/')
    addLog('info', `输出目录: ${outputPath}`)
    addLog('info', `扫描类型: ${scanParams.type === 'frequency' ? '频率' : '电压'}扫描 | 扫描参数: ${scanParams.start} → ${scanParams.stop} (步长: ${scanParams.step}) | 扫描长度: ${scanParams.length}`)
    addLog('info', `线程数: ${cpuCores} (CPU核心数)`)
    addLog('info', '========================')
    
    // 更新状态为运行中
    currentStatus.value = SIMULATION_STATUS.RUNNING
    statusText.value = t('status.running')
    isRunning.value = true
    
    // 开始轮询Python日志
    startLogPolling()
    
    // 调用Python后端
    const result = await (window as any).electronAPI.runSimionAutomation(config)
    
    if (result.success) {
      ElMessage.success({
        message: t('messages.automationStarted'),
        duration: 3000
      })
      addLog('success', 'SIMION自动化任务已启动')
      
      // 延迟检查任务状态，给任务一些时间启动
      setTimeout(() => {
        checkTaskStatus()
      }, 2000) // 2秒后开始检查
    } else {
      ElMessage.error(`${t('messages.runAutomationFailed')}: ${result.error || t('common.error')}`)
      addLog('error', `启动失败: ${result.error || '未知错误'}`)
      // 启动失败时停止日志轮询并重置状态
      stopLogPolling()
      currentStatus.value = SIMULATION_STATUS.WAITING
      statusText.value = '准备就绪'
      isRunning.value = false
    }
  } catch (error) {
    ElMessage.error(`${t('messages.runAutomationFailed')}: ${error}`)
    addLog('error', `运行失败: ${error}`)
    // 出错时也重置状态
    isRunning.value = false
  }
}

// 停止SIMION自动化
const stopAutomation = async () => {
  try {
    addLog('info', '正在停止SIMION自动化...')
    
    // 调用Python后端停止自动化
    if ((window as any).electronAPI && (window as any).electronAPI.stopSimionAutomation) {
      const result = await (window as any).electronAPI.stopSimionAutomation()
      
      if (result.success) {
        ElMessage.success({
          message: t('messages.automationStopped'),
          duration: 3000
        })
        addLog('success', 'SIMION自动化已停止')
      } else {
        ElMessage.warning(`${t('messages.stopCommandSent')}: ${result.error || t('common.error')}`)
        addLog('warn', `停止命令已发送: ${result.error || '未知错误'}`)
      }
    } else {
      ElMessage.warning(t('messages.stopFunctionUnavailable'))
      addLog('warn', '停止功能不可用，强制重置状态')
    }
    
    // 强制停止日志轮询
    stopLogPolling()
    
    // 重置状态
    currentStatus.value = SIMULATION_STATUS.WAITING
    statusText.value = '准备就绪'
    isRunning.value = false
    
    addLog('info', '状态已重置为准备就绪')
    
  } catch (error) {
    ElMessage.error(`${t('messages.stopAutomationFailed')}: ${error}`)
    addLog('error', `停止失败: ${error}`)
    
    // 即使出错也要重置状态
    stopLogPolling()
    currentStatus.value = SIMULATION_STATUS.WAITING
    statusText.value = '准备就绪'
    isRunning.value = false
  }
}

// 设置页面状态
const showSettings = ref(false)



// 全局键盘事件处理
const onGlobalKeyDown = (event: KeyboardEvent) => {
  // Ctrl+B 切换侧边栏
  if (event.ctrlKey && event.key === 'b') {
    event.preventDefault()
    toggleSidebar()
  }
  
  // Shift+Alt+R 在文件资源管理器中显示
  if (event.shiftKey && event.altKey && event.key === 'R') {
    event.preventDefault()
    revealInExplorer()
  }
  
  // Shift+Alt+C 复制路径
  if (event.shiftKey && event.altKey && event.key === 'C') {
    event.preventDefault()
    copyPath()
  }
  
  // Ctrl+M 然后 Ctrl+Shift+C 复制相对路径
  if (event.ctrlKey && event.key === 'm') {
    event.preventDefault()
    // 这里可以设置一个状态，等待下一个组合键
    ElMessage.info(t('messages.copyRelativePathHint'))
  }
  
  // Shift+Alt+F 在文件夹中查找
  if (event.shiftKey && event.altKey && event.key === 'F') {
    event.preventDefault()
    findInFolder()
  }
}

// 保存监听器函数引用
let settingsMenuHandler: (() => void) | null = null

// 生命周期
onMounted(() => {
  currentProject.value = projectService.getCurrentProject()
  if (currentProject.value) {
    loadProjectFiles()
  } else {
    navigateTo('/welcome')
  }
  
  // 添加全局键盘事件监听
  document.addEventListener('keydown', onGlobalKeyDown)
  
  // 添加点击外部隐藏菜单的事件监听
  document.addEventListener('click', hideContextMenu)
  // 点击空白也关闭新建输入
  document.addEventListener('click', () => { showNewFileInput.value = false })
  
  // 监听菜单事件
  const electronAPI = (window as any).electronAPI
  if (electronAPI && typeof electronAPI.on === 'function') {
    console.log('Electron API available, setting up menu event listeners')
    
    // 设置菜单
    settingsMenuHandler = () => {
      showSettings.value = true
    }
    electronAPI.on('menu-open-settings', settingsMenuHandler)
    
    // 编辑参数菜单
    electronAPI.on('menu-edit-params', () => {
      showSettings.value = true
    })
    
    // 重置参数菜单
    electronAPI.on('menu-reset-params', () => {
      // 重置全局设置到默认值
      const globalSettings = useGlobalSettingsStore()
      globalSettings.resetToDefaults()
      ElMessage.success({
        message: t('messages.settingsReset'),
        duration: 3000
      })
    })
    
    // 保存文件菜单
    electronAPI.on('menu-save-file', () => {
      saveFile()
    })
    
    // 撤销菜单
    electronAPI.on('menu-undo', () => {
      undoEdit()
    })
  } else {
    console.log('Electron API not available or on method missing:', {
      electronAPI: !!electronAPI,
      onMethod: electronAPI ? typeof electronAPI.on : 'N/A'
    })
  }
})

onUnmounted(() => {
  // 停止轮询Python日志
  stopLogPolling()
  
  // 清理全局键盘事件监听
  document.removeEventListener('keydown', onGlobalKeyDown)
  
  // 清理点击事件监听
  document.removeEventListener('click', hideContextMenu)
  document.removeEventListener('click', () => { showNewFileInput.value = false })
  
  // 清理菜单事件监听
  const electronAPI = (window as any).electronAPI
  if (electronAPI && typeof electronAPI.off === 'function') {
    if (settingsMenuHandler) {
      electronAPI.off('menu-open-settings', settingsMenuHandler)
      settingsMenuHandler = null
    }
    
    // 清理其他菜单事件监听器
    electronAPI.off('menu-save-file', () => {})
    electronAPI.off('menu-undo', () => {})
    electronAPI.off('menu-edit-params', () => {})
    electronAPI.off('menu-reset-params', () => {})
  }
})
</script>

<style scoped>
.ide-layout {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: #1e1e1e;
  color: #cccccc;
  overflow: hidden;
}

.ide-toolbar {
  height: 50px;
  background: #2d2d30;
  border-bottom: 1px solid #3e3e42;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 16px;
  flex-shrink: 0;
}

.toolbar-left,
.toolbar-right {
  display: flex;
  align-items: center;
  gap: 12px;
}

.project-info {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 4px 8px;
  background: #0e639c;
  border-radius: 4px;
  font-size: 14px;
  color: white;
}

.project-name {
  font-weight: 500;
  max-width: 200px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.ide-content {
  flex: 1;
  display: flex;
  overflow: hidden;
}

.file-explorer {
  width: 300px;
  background: #252526;
  border-right: 1px solid #3e3e42;
  display: flex;
  flex-direction: column;
  flex-shrink: 0;
  transition: width 0.2s ease;
}

/* 拖拽条样式 */
.resize-handle {
  width: 4px;
  background: #3e3e42;
  cursor: col-resize;
  flex-shrink: 0;
  transition: background-color 0.2s ease;
}

.resize-handle:hover {
  background: #007acc;
}

.resize-handle:active {
  background: #007acc;
}

/* 侧边栏切换按钮 */
.sidebar-toggle {
  color: #ccc !important;
  transition: all 0.2s ease;
}

.sidebar-toggle:hover {
  color: #007acc !important;
  background-color: rgba(0, 122, 204, 0.1) !important;
}

/* 右键菜单样式 */
.context-menu {
  position: fixed;
  background: #2d2d30;
  border: 1px solid #3e3e42;
  border-radius: 4px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
  z-index: 1000;
  min-width: 200px;
  padding: 4px 0;
  font-size: 13px;
}

.context-menu-item {
  display: flex;
  align-items: center;
  padding: 6px 12px;
  color: #cccccc;
  cursor: pointer;
  transition: background-color 0.1s ease;
  position: relative;
}

.context-menu-item:hover {
  background-color: #094771;
}

.context-menu-item .el-icon {
  margin-right: 8px;
  font-size: 14px;
  color: #cccccc;
}

.context-menu-item span:not(.shortcut) {
  flex: 1;
}

.context-menu-item .shortcut {
  color: #888;
  font-size: 11px;
  margin-left: 8px;
}

.context-menu-separator {
  height: 1px;
  background: #3e3e42;
  margin: 4px 0;
}

/* 新建文件浮层样式 */
.new-file-popover {
  position: fixed;
  z-index: 1001;
}
.new-file-inner {
  display: flex;
  align-items: center;
  background: #1e1e1e;
  border: 1px solid #3e3e42;
  border-radius: 4px;
  padding: 4px 8px;
  min-width: 260px;
}
.new-file-input {
  flex: 1;
  background: transparent;
  border: none;
  outline: none;
  color: #ddd;
  font-size: 13px;
}
.nf-icon {
  color: #999;
  margin-right: 8px;
}

.explorer-header {
  height: 40px;
  background: #2d2d30;
  border-bottom: 1px solid #3e3e42;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 16px;
}

.explorer-header h3 {
  margin: 0;
  font-size: 14px;
  font-weight: 600;
  color: #cccccc;
}

.file-tree {
  flex: 1;
  overflow-y: auto;
  padding: 8px;
}

.file-tree-component {
  background: transparent;
  color: #cccccc;
}

.tree-node {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 2px 0;
  cursor: pointer;
  transition: background-color 0.2s ease;
  border-radius: 3px;
}

.tree-node:hover {
  background-color: rgba(255, 255, 255, 0.05);
}

.file-name {
  font-size: 13px;
  user-select: none;
}

/* 文件夹展开动画 */
.el-tree-node__children {
  transition: all 0.3s ease;
}

/* 文件夹图标样式 */
.el-tree-node__expand-icon {
  transition: transform 0.2s ease;
}

.el-tree-node__expand-icon.is-leaf {
  opacity: 0.3;
}

.editor-area {
  flex: 1;
  display: flex;
  flex-direction: column;
  background: #1e1e1e;
}

.editor-tabs {
  height: 40px;
  background: #2d2d30;
  border-bottom: 1px solid #3e3e42;
  display: flex;
  align-items: center;
  overflow-x: auto;
  flex-shrink: 0;
}

.tab-item {
  height: 100%;
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 0 16px;
  background: #2d2d30;
  border-right: 1px solid #3e3e42;
  cursor: pointer;
  transition: background-color 0.2s;
  min-width: 120px;
}

.tab-item:hover {
  background: #37373d;
}

.tab-item.active {
  background: #1e1e1e;
  border-bottom: 2px solid #007acc;
}

.tab-name {
  font-size: 13px;
  color: #cccccc;
}

.modified-indicator {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background-color: #ff6b6b;
  display: inline-block;
  margin-left: 4px;
  flex-shrink: 0;
}

.tab-close {
  margin-left: auto;
  opacity: 0.7;
}

.tab-close:hover {
  opacity: 1;
}


.code-editor {
  flex: 1;
  display: flex;
  flex-direction: column;
  background: #1e1e1e;
}

.editor-header {
  height: 40px;
  background: #2d2d30;
  border-bottom: 1px solid #3e3e42;
  display: flex;
  align-items: center;
  justify-content: flex-start;
  padding: 0 16px;
  flex-shrink: 0;
}

.file-path {
  font-size: 12px;
  color: #888;
  font-family: 'Consolas', 'Monaco', monospace;
}

.ide-toolbar .breadcrumb.file-path {
  margin-left: 12px;
  color: #c0c4cc;
  font-size: 12px;
  max-width: 50vw;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.editor-actions {
  display: flex;
  gap: 8px;
}

.editor-content {
  flex: 1;
  padding: 16px;
  overflow: hidden;
}

.code-textarea {
  width: 100%;
  height: 100%;
  background: #1e1e1e;
  color: #cccccc;
  border: none;
  outline: none;
  font-family: 'Consolas', 'Monaco', monospace;
  font-size: 14px;
  line-height: 1.5;
  resize: none;
  padding: 0;
}

.code-textarea::placeholder {
  color: #666;
}

.empty-editor {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #1e1e1e;
}



/* 日志面板样式已移至LogPanel组件 */

/* 响应式设计 */
@media (max-width: 768px) {
  .file-explorer {
    width: 250px;
  }
  
  .ide-toolbar {
    padding: 0 8px;
  }
  
  .project-name {
    max-width: 150px;
  }
}

@media (max-width: 480px) {
  .file-explorer {
    width: 200px;
  }
  
  .tab-item {
    min-width: 100px;
    padding: 0 8px;
  }
  
  .editor-header {
    padding: 0 8px;
  }
}

/* 运行按钮样式 */
.run-button {
  display: flex;
  align-items: center;
  gap: 4px;
}

.run-button .el-icon {
  font-size: 14px;
}
</style>
